%%%-------------------------------------------------------------------
%%% @author root
%%% @copyright (C) 2016, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 14. 二月 2016 下午8:52
%%%-------------------------------------------------------------------
-module(cus_emotion_edit_handler).
-behaviour(cowboy_http_handler).

-include("cus.hrl").

-export([init/3]).
-export([handle/2]).
-export([terminate/3]).




init(_Type, Req, _Opts) ->
  {ok, Req, undefined_state}.

handle(Req, State) ->
  {Method,_} = cowboy_req:method(Req),
  HasBody = cowboy_req:has_body(Req),
  {CookieVal, Req2} = cowboy_req:cookie(<<"sessionid">>, Req),
%%  check SessionID and refresh cookie
  case cus_util:filter(CookieVal) of
    {true,UserName, PassWord} ->
      SessionID = cus_util:get_session_id(UserName,PassWord),
      Req3 = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, [
        {max_age, ?COOKIE_TIME}
      ], Req2),
      {ok,Req4} = maybe_echo(Method, HasBody, Req3),
      {ok, Req4, State};
    _->
      {ok, Body} = login_dtl:render([
      ]),
      {ok,Req3} = echo(Body, Req2),
      {ok, Req3, State}
  end.

terminate(_Reason, _Req, _State) ->
  ok.

maybe_echo(<<"GET">>, false, Req) ->
  {PacketId,Req2} = cowboy_req:qs_val(<<"packetId">>,Req),
  {Name,Req2} = cowboy_req:qs_val(<<"name">>,Req),
  case PacketId of
   undefined ->
     IdList1 =[Packet#cus_sys_emotion_packet.id||Packet<- cus_redis:get_sys_emotion_packets()],
     SeqIdList = case IdList1 of
                   [] ->
                     [];
                   _->
                     lists:seq(1,?l2i(lists:max(IdList1)))
                 end,
     Data = [[Packet#cus_sys_emotion_packet.id,
       Packet#cus_sys_emotion_packet.name,
       Packet#cus_sys_emotion_packet.displayOrder,
       Packet#cus_sys_emotion_packet.directory,
       Packet#cus_sys_emotion_packet.available,
       Packet#cus_sys_emotion_packet.cover,
       Packet#cus_sys_emotion_packet.code,
       Packet#cus_sys_emotion_packet.detail,
       Packet#cus_sys_emotion_packet.emotions]||Packet <-lists:reverse(cus_util:get_emotion_packets(SeqIdList,[]))],
     {ok, Body} = cus_emotion_packet_list_dtl:render([
       {data,Data}
     ]),
     echo(Body, Req2);
   _->
     Packet =cus_redis:get_sys_emotion_packet(PacketId),
     Emotions = Packet#cus_sys_emotion_packet.emotions,
     Emotion = lists:keyfind(?b2l(Name),2,Emotions),
     DisplayOrders1  = [{Emotion1#cus_sys_emotion.displayOrder++"_"}||Emotion1<-Emotions],
     DisplayOrders2 = lists:keydelete(Emotion#cus_sys_emotion.displayOrder++"_",1,DisplayOrders1),
     DisplayOrders = [tuple_to_list(DisplayOrder)||DisplayOrder <- DisplayOrders2],
     lager:info("========~p~n",[DisplayOrders]),

     {ok, Body} = cus_emotion_add_dtl:render([
       {displayOrders,DisplayOrders},
       {packetId,PacketId},
       {name,Emotion#cus_sys_emotion.name},
       {displayOrder,Emotion#cus_sys_emotion.displayOrder},
       {filename,Emotion#cus_sys_emotion.fileName},
       {code,Emotion#cus_sys_emotion.code},
       {available,Emotion#cus_sys_emotion.available},
       {url,Emotion#cus_sys_emotion.url},
       {urlJpg,Emotion#cus_sys_emotion.urlJpg}
     ]),
     echo(Body, Req2)
 end;


maybe_echo(<<"POST">>, true, Req) ->
  {ok, PostVals, Req2} = cowboy_req:body_qs(Req),
  PacketId =?param(<<"packetId">>,PostVals),
  Name =?param(<<"oldName">>,PostVals),
  Packet =cus_redis:get_sys_emotion_packet(PacketId),
  EmotionList = Packet#cus_sys_emotion_packet.emotions,
  NewEmotion = #cus_sys_emotion{
                  name = ?param(<<"name">>,PostVals),
                  displayOrder = ?param(<<"displayOrder">>,PostVals),
                  fileName = ?param(<<"fileName">>,PostVals),
                  code = ?param(<<"code">>,PostVals),
                  available = ?param(<<"available">>,PostVals),
                  url = ?param(<<"url">>,PostVals),
                  urlJpg = ?param(<<"urlJpg">>,PostVals)
              },

  Emotions = lists:keyreplace(Name,2,EmotionList,NewEmotion),
  NewPacket = Packet#cus_sys_emotion_packet{
    emotions = Emotions
  },
  cus_redis:set_sys_emotion_packets(NewPacket),

  Data = [[Emotion#cus_sys_emotion.name,
    Emotion#cus_sys_emotion.displayOrder,
    Emotion#cus_sys_emotion.fileName,
    Emotion#cus_sys_emotion.code,
    Emotion#cus_sys_emotion.available,
    Emotion#cus_sys_emotion.url,
    Emotion#cus_sys_emotion.urlJpg]||Emotion <-Emotions],
  {ok, Body} = cus_emotion_packet_detail_dtl:render([
    {packetId,PacketId},
    {data,Data}
  ]),
  echo(Body, Req2);


maybe_echo(<<"POST">>, false, Req) ->
  {ok, Body} = failed_dtl:render([
    {errorMsg,"Missing body"}
  ]),
  cowboy_req:reply(400, [{<<"content-type">>, <<"text/html; charset=utf-8">>}], Body, Req);
maybe_echo(_, _, Req) ->

  {ok, Body} = failed_dtl:render([
    {errorMsg,"405"}
  ]),
  cowboy_req:reply(405, [{<<"content-type">>, <<"text/html; charset=utf-8">>}], Body, Req).


echo(undefined, Req) ->
  {ok, Body} = failed_dtl:render([
    {errorMsg,"system error"}
  ]),
  cowboy_req:reply(400, [{<<"content-type">>, <<"text/html; charset=utf-8">>}], Body, Req);
echo(Body, Req) ->
  cowboy_req:reply(200, [
    {<<"content-type">>, <<"text/html; charset=utf-8">>}
  ], Body, Req).

